import 'dart:async';
import 'dart:convert';
import 'dart:io';
import 'dart:math';

import 'package:flutter/foundation.dart';
import 'package:network_info_plus/network_info_plus.dart';
import 'package:shelf/shelf_io.dart';
import 'package:shelf_web_socket/shelf_web_socket.dart';
import 'package:web_socket_channel/web_socket_channel.dart';
import 'package:ws_group_chat/model/chat_model.dart';

class HostData extends ChangeNotifier {
  String userName = "Player${Random().nextInt(1000000)}";
  bool isHost = true;
  int playersCount = 1; // 默认1个玩家
  String? wsUrl;
  final List<WebSocketChannel> _connectedClients = [];
  final _port = 9423;
  // 定时给所有客户端同步主机的消息
  Timer? _asyncHostDataTimer;
  HttpServer? _server;
  bool isChatting = false;
  List<ChatModel> chatMessages = [];

  // 主机模式：启动服务器
  Future<bool> startServer() async {
    try {
      final handle = webSocketHandler((WebSocketChannel channel) {
        // onConnect的回调
        _connectedClients.add(channel);
        playersCount++;
        notifyListeners();
        channel.stream.listen(
          (msg) => _handleComingMessage(msg, channel),
          onDone: () => onDoneAndError(channel),
          onError: (error) => onDoneAndError(channel),
        );
      });
      _server = await serve(handle, InternetAddress.anyIPv4, _port);
      _startAsyncHostDataTimer();
      notifyListeners();
      return true;
    } catch (e) {
      print(e);
      return false;
    }
  }

  Future<bool> getWsUrl() async {
    try {
      final networkInfo = NetworkInfo();
      final server = await networkInfo.getWifiIP();
      wsUrl = "ws://$server:$_port";
      notifyListeners();
      print(wsUrl);
      return true;
    } catch (e) {
      print(e);
      return false;
    }
  }

  // 广播消息给所有客户端
  void _broadcastToAllClients(String message) {
    print('开始广播消息 $message 给 ${_connectedClients.length} 个客户端');
    if (_connectedClients.isEmpty) return;
    for (var client in _connectedClients) {
      try {
        client.sink.add(message);
        print('消息发送成功');
      } catch (e) {
        print('消息发送失败: $e');
        // _connectedClients.remove(client);
        // notifyListeners();
      }
    }
  }

  void _startAsyncHostDataTimer() {
    _asyncHostDataTimer?.cancel();
    _asyncHostDataTimer = Timer.periodic(const Duration(milliseconds: 300), (
      timer,
    ) {
      _broadcastToAllClients(
        jsonEncode({
          'type': 'hostData',
          'data': {'playerCount': playersCount, 'isChatting': isChatting},
        }),
      );
    });
  }

  void startChatRoom() {
    isChatting = true;
    _broadcastToAllClients(jsonEncode({'type': 'startChatRoom'}));
  }

  void onDoneAndError(WebSocketChannel channel) {
    _connectedClients.remove(channel);
    playersCount--;
    notifyListeners();
  }

  void _handleComingMessage(dynamic rawMsg, WebSocketChannel sender) {
    try {
      final msg = jsonDecode(rawMsg);
      if (msg['type'] == 'chat_msg') {
        final chatModel = ChatModel.fromJson(
          jsonDecode(msg['data']['chat_model']),
        );
        chatMessages.add(chatModel);
        notifyListeners();
        _broadcastToAllClients(
          jsonEncode({
            'type': 'chat_msg',
            'data': {'chat_model': chatModel.toJsonString()},
          }),
        );
      }
    } catch (e) {
      print(e);
      print(rawMsg);
    }
  }

  void sendMessage(String message) {
    final chatModel = ChatModel(userName: userName, msg: message);
    chatMessages.add(chatModel);
    notifyListeners();
    _broadcastToAllClients(
      jsonEncode({
        'type': 'chat_msg',
        'data': {'chat_model': chatModel.toJsonString()},
      }),
    );

  }

  void close() {
    print('close');
    playersCount = 1;
    wsUrl = null;
    _server?.close();
    _asyncHostDataTimer?.cancel();
    _asyncHostDataTimer = null;
    _server = null;
    _connectedClients.clear();
  }
}
